const Router = require('koa-router')
const router = new Router()
const { USER_REGISTER, USER_LOGIN, USER_INFO } = require('./consts')
const { SuccessModel, ErrorModel } = require('../model/result')
const { handleUserRegister, handleUserLogin } = require('../controller/user')
const { authFail } = require('../config/error/user')

// 路由前缀
router.prefix('/api/user')
// 处理用户相关路由
router.get(USER_INFO, (ctx, next) => {
  console.log('ctx.session,', ctx.session)
  // 无权限
  if (!ctx.session.username) {
    ctx.body = new ErrorModel(authFail)
  }
  ctx.body = new SuccessModel({
    message: '用户信息获取',
    data: {
      username: 'chigga',
      age: 18
    }
  })
})
router.post(USER_REGISTER, async (ctx, next) => {
  const { request } = ctx
  // 用户注册
  const result = await handleUserRegister(request.body)
  ctx.body = result
})
router.post(USER_LOGIN, async (ctx, next) => {
  const { request } = ctx
  // 用户登录
  const result = await handleUserLogin(request.body)
  // 保存登录状态
  if (result.code === 200) {
    const { username, password, gender } = result.data
    // 同步到Redis中
    ctx.session.username = username
    ctx.session.password = password
    ctx.session.gender = gender
  }
  ctx.body = result
})

module.exports = router
